<?php

namespace app\gov\controller;

use app\gov\model\UserAreaModel;
use think\admin\Controller;
use think\admin\extend\DataExtend;
use think\admin\helper\QueryHelper;
use think\admin\model\SystemAuth;
use think\admin\model\SystemBase;
use think\admin\model\SystemUser;
use think\admin\service\AdminService;
use think\facade\Db;

/**
 * 审批用户管理
 * @class User
 * @package app\admin\controller
 */
class User extends Controller
{
    /**
     * 审批用户管理
     * @auth true
     * @menu true
     */
    public function index()
    {
        $this->type = $this->get['type'] ?? 'index';
        SystemUser::mQuery()->layTable(function () {
            $this->title = '审批用户管理';
            $this->bases = SystemBase::items('身份权限');
        }, function (QueryHelper $query) {
            // 加载对应数据列表
            $query->where(['is_deleted' => 0, 'status' => intval($this->type === 'index')]);
            // 关联用户身份资料
            $query->with(['userinfo' => static function ($query) {
                $query->field('code,name,content');
            }]);
            // 只显示审批用户
            $query->where('usertype', 'gov_admin');
            // 数据列表搜索过滤
            $query->equal('status')->dateBetween('login_at,create_at');
            $query->like('username|nickname#username,contact_phone#phone,contact_mail#mail');
        });
    }

    /**
     * 列表数据处理
     * @param array $data
     */
    protected function _index_page_filter(array &$data)
    {
        foreach ($data as &$vo){
            $vo['user_area'] = UserAreaModel::where('gov_user_id', $vo['id'])->find();
        }
    }

    /**
     * 添加审批用户
     * @auth true
     */
    public function add()
    {
        SystemUser::mForm('form');
    }

    /**
     * 编辑审批用户
     * @auth true
     */
    public function edit()
    {
        SystemUser::mForm('form');
    }

    /**
     * 修改审批用户密码
     * @auth true
     */
    public function pass()
    {
        $this->_applyFormToken();
        if ($this->request->isGet()) {
            $this->verify = false;
            SystemUser::mForm('pass');
        } else {
            $data = $this->_vali([
                'id.require'                  => '用户ID不能为空！',
                'password.require'            => '登录密码不能为空！',
                'repassword.require'          => '重复密码不能为空！',
                'repassword.confirm:password' => '两次输入的密码不一致！',
            ]);
            $user = SystemUser::mk()->findOrEmpty($data['id']);
            if ($user->isExists()) {
                if ($user->usertype != 'gov_admin') $this->error('没有权限，账号身份不正确');
                if ($user->save(['password' => md5($data['password'])])){
                    // 修改密码同步事件处理
                    $this->app->event->trigger('PluginAdminChangePassword', [
                        'uuid' => $data['id'], 'pass' => $data['password']
                    ]);
                    sysoplog('审批用户管理', "修改审批用户[{$data['id']}]密码成功");
                    $this->success('密码修改成功，请使用新密码登录！', '');
                }else{
                    $this->error('密码修改失败，请稍候再试！');
                }
            } else {
                $this->error('账号不存在！');
            }
        }
    }

    /**
     * 表单数据处理
     * @param array $data
     */
    protected function _form_filter(array &$data)
    {
        if ($this->request->isPost()) {
            // 固定审批用户的权限为id=3
            $data['authorize'] = [3];
            $data['usertype'] = 'gov_admin';
            // 检查用户类型
            if (!empty($data['id'])) {
                $user = SystemUser::mk()->find($data['id']);
                if (empty($user)) $this->error('账号不存在');
                if ($user->usertype != 'gov_admin') $this->error('没有权限，账号身份不正确');
            }
            // 检查资料是否完整
            empty($data['username']) && $this->error('登录账号不能为空！');
            if ($data['username'] !== AdminService::getSuperName()) {
                empty($data['authorize']) && $this->error('未配置权限！');
            }
            // 处理上传的权限格式
            $data['authorize'] = arr2str($data['authorize'] ?? []);
            if (empty($data['id'])) {
                // 检查账号是否重复
                $map = ['username' => $data['username'], 'is_deleted' => 0];
                if (SystemUser::mk()->where($map)->count() > 0) {
                    $this->error("账号已经存在，请使用其它账号！");
                }
                // 新添加的用户密码与账号相同
                $data['password'] = md5($data['username']);
            } else {
                unset($data['username']);
            }

            // 更新审批地区数据
            if (empty($data['province'])) $this->error('请选择审批省份');
            if (empty($data['city'])) $this->error('请选择审批城市');
//            if (empty($data['area'])) $this->error('请选择审批区县');

        } else {
            // 权限绑定处理
            $data['authorize'] = str2arr($data['authorize'] ?? '');
            $this->auths = SystemAuth::items();
            $this->bases = SystemBase::items('身份权限');
            $this->super = AdminService::getSuperName();
            // 获取地区信息
            $area_list = Db::name('Area')->order('id asc')->column('id,pid,ext_name as name');
            $this->area_list = DataExtend::arr2tree($area_list, 'id', 'pid','children');
            // 获取审批地区数据
            if (!empty($data['id'])) {
                $data['user_area'] = UserAreaModel::where('gov_user_id', $data['id'])->find();
            } else {
                $data['user_area'] = [];
            }
        }
    }

    protected function _form_result(bool $res, array $data){
        if (!$res) return;
        $id = $data['id'];
        $userArea = UserAreaModel::where('gov_user_id', $id)->findOrEmpty();
        $userArea->gov_user_id = $id;
        $userArea->province = $data['province'];
        $userArea->city = $data['city'];
//        $userArea->area = $data['area'];
        $userArea->save();
    }


    /**
     * 修改审批用户状态
     * @auth true
     */
    public function state()
    {
        $this->_checkInput();
        SystemUser::mSave($this->_vali([
            'status.in:0,1'  => '状态值范围异常！',
            'status.require' => '状态值不能为空！',
        ]));
    }

    /**
     * 删除审批用户
     * @auth true
     */
    public function remove()
    {
        $this->_checkInput();
        SystemUser::mDelete();
    }

    /**
     * 检查输入变量
     */
    private function _checkInput()
    {
        $ids = str2arr(input('id', ''));
        $users = SystemUser::mk()->where(['id' => $ids])->select();
        foreach ($users as $user){
            if ($user->usertype != 'gov_admin') $this->error('没有权限，账号身份不正确');
        }
        if (in_array('10000', str2arr(input('id', '')))) {
            $this->error('系统超级账号禁止删除！');
        }
    }
}
